<template>
  <div class="app-container">
<el-tree
      :data="categoryDTOList"
      show-checkbox
      :props="myProps"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => append(data)" v-if="data.level==1 || data.level==2">
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)" v-if="node.childNodes.length == 0">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import categoryApi from '../../api/product/category.js'
export default {

  data() {
    return {
      id:'',
      categoryDTOList:[],//三级ID， category1_id,category2_id,category3_id
      myProps:{
         value:'id',
         label:'name'
      }
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
  },

  // 生命周期函数：内存准备完毕，页面渲染成功
  mounted() {
    this.findCategoryTree();
  },

  methods: {
    findCategoryTree(){
      categoryApi.findCategoryTree().then(res=>{
        this.categoryDTOList = res.data.data;
      })
    },
    categoryDTOChange(){

    },
    append(data) {
      debugger
      const newChild = { id: this.id++, name: '添加的内容', children: [] };
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
    },

    remove(node, data) {
      console.log(node)
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
  }
}
</script>

<style>
 .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>


